package com.chensheng.controller;

import com.chensheng.constant.CookieConstant;
import com.chensheng.constant.RedisConstant;
import com.chensheng.enums.ResultErrorEnum;
import com.chensheng.form.SellerInfoForm;
import com.chensheng.model.SellerInfo;
import com.chensheng.redis.RedisConfig;
import com.chensheng.redis.RedisService;
import com.chensheng.service.SellerInfoService;
import com.chensheng.util.CookieUtil;
import com.chensheng.util.KeyUtil;
import com.sun.javafx.binding.StringFormatter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/seller/user")
@Slf4j
public class SellerUserController {

    @Autowired
    private SellerInfoService sellerInfoService;

    @Autowired
    private RedisService redisService;

    @PostMapping("/do_register")
    public ModelAndView doRegister(@Valid SellerInfoForm sellerInfoForm,
                                 BindingResult bindingResult,
                                 Map<String, Object> map){
        if(bindingResult.hasErrors()){
            map.put("msg", bindingResult.getFieldError());
            map.put("url", "/seller/user/register");
            return new ModelAndView("common/error", map);
        }

        SellerInfo sellerInfo = new SellerInfo();
        sellerInfo.setSellerId(KeyUtil.genUniqueKey());
        sellerInfo.setUsername(sellerInfoForm.getUsername());
        sellerInfo.setPassword(sellerInfoForm.getPassword());
        Date date = new Date();
        sellerInfo.setCreateTime(date);
        sellerInfo.setUpdateTime(date);

        //查询数据库是否有此主键
        SellerInfo sellerInfo1 = sellerInfoService.findByUserName(sellerInfo.getUsername());
        if(sellerInfo1 != null){
            map.put("msg", "用户名已存在");
            map.put("url", "/seller/user/register");
            return new ModelAndView("common/error", map);
        }

        //插入数据库
        sellerInfoService.save(sellerInfo);

        map.put("msg", "用户注册成功");
        map.put("url", "/seller/product/list");
        return new ModelAndView("common/success", map);
    }

    @PostMapping("/do_login")
    public ModelAndView doLogin(@Valid SellerInfoForm sellerInfoForm,
                                 BindingResult bindingResult,
                                 HttpServletResponse response,
                                 Map<String, Object> map){
        if(bindingResult.hasErrors()){
            map.put("msg", bindingResult.getFieldError());
            map.put("url", "/seller/user/login");
            return new ModelAndView("common/error", map);
        }

        SellerInfo sellerInfo = sellerInfoService.findByUserName(sellerInfoForm.getUsername());
        if(sellerInfo == null || !sellerInfo.getPassword().equals(sellerInfoForm.getPassword())){
            map.put("msg", "用户名或者密码错误");
            map.put("url", "/seller/user/login");
            return new ModelAndView("common/error", map);
        }

        //2. 设置token到redis
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;

        redisService.set(String.format(RedisConstant.TOKEN_PREFIX, token), sellerInfo.getSellerId());

        //设置token到Cookie
        CookieUtil.set(response, CookieConstant.TOKEN, token, expire);

        map.put("msg", "用户登陆成功");
        map.put("url", "/seller/product/list");
        return new ModelAndView("common/success", map);
    }

    @GetMapping("/logout")
    public ModelAndView doLogout(HttpServletRequest request,
                                 HttpServletResponse response,
                                 Map<String, Object> map){
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
        if(cookie != null){
            //清除redis
            redisService.delete(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));

            //清除cookie
            CookieUtil.set(response, cookie.getName(), null, 0);
        }

        map.put("msg", ResultErrorEnum.LOGOUT_SUCCESS.getMsg());
        map.put("url", "/seller/user/login");

        return new ModelAndView("common/success", map);
    }

    @GetMapping("/register")
    public ModelAndView register(){
        return new ModelAndView("user/register");
    }

    @GetMapping("/login")
    public ModelAndView login(){
        return new ModelAndView("user/login");
    }

}
